package com.gzhryc.shared_device.bxscn.code;

import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.common.redis.RedisTools;
import com.gzhryc.common.secruity.EncryptTools;

/**
 * 充电插座工作缓存管理
 * @version 2022-11-07
 */
public class BXSCNWorkCacheManager {

    static Logger log = Logger.getLogger(BXSCNWorkCacheManager.class);

    static BXSCNWorkCacheManager me;

    public static BXSCNWorkCacheManager self() {
        if (me == null) {
            me = new BXSCNWorkCacheManager();
        }
        return me;
    }

    Long times = 600L;
    Integer redisDB = null;

    public void initial(Integer redisDB) {
        this.redisDB = redisDB;
    }

    public boolean setData(String msgId, DeviceWorkInfo deviceWorkInfo) {
        try {
            String key = EncryptTools.md5(deviceWorkInfo.deviceSn + "_" + msgId);
            if (!RedisTools.get().exists(redisDB, key)) {
                if (RedisTools.get().set(redisDB, key, JsonTools.toJson(deviceWorkInfo), times)) {
                    return true;
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return false;
    }

    public DeviceWorkInfo getAndRemoveData(String deviceSn, String msgId) {
        try {
            String key = EncryptTools.md5(deviceSn + "_" + msgId);
            String json = RedisTools.get().getAndRemove(redisDB, key);
            if (JsonTools.isJsonStr(json)) {
                return JsonTools.fromJson(json, DeviceWorkInfo.class);
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return null;
    }

    /**
     * 设备工作信息
     */
    public static class DeviceWorkInfo {

        private String deviceSn;
        private Integer slotNum;
        private String tradeNo;

        public String getDeviceSn() {
            return deviceSn;
        }

        public void setDeviceSn(String deviceSn) {
            this.deviceSn = deviceSn;
        }

        public Integer getSlotNum() {
            return slotNum;
        }

        public void setSlotNum(Integer slotNum) {
            this.slotNum = slotNum;
        }

        public String getTradeNo() {
            return tradeNo;
        }

        public void setTradeNo(String tradeNo) {
            this.tradeNo = tradeNo;
        }
    }
}
